<?php

/**
 * This is the model class for table "user".
 *
 * The followings are the available columns in table 'user':
 * @property integer $id
 * @property string $name
 * @property string $email
 * @property string $password
 * @property string $birthday
 * @property integer $sex
 * @property string $avatar
 * @property string $cover
 * @property string $other
 * @property integer $admin
 * @property string $lastlogin
 *
 * The followings are the available model relations:
 * @property Comment[] $comments
 * @property Friendship[] $friendships
 * @property Friendship[] $friendships1
 * @property Listmusic[] $listmusics
 * @property Messenger[] $messengers
 * @property Messenger[] $messengers1
 * @property Music[] $musics
 * @property Notification[] $notifications
 * @property Tag[] $tags
 */
class User extends CActiveRecord
{
	public $verifyCode;

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'user';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('name, email, password, birthday, sex', 'required',
				'message'=>'Không bỏ trống {attribute}.'),
			array('password', 'length', 'max'=>50,'min'=>6,
				'tooShort'=>'{attribute} phải ít nhất 6 ký tự, tối đa 50 ký tự '),
			array('name, email', 'length', 'max'=>50,'min'=>12,
				'tooShort'=>'{attribute} phải ít nhất 12 ký tự, tối đa 50 ký tự '),
			array('birthday', 'date', 'format'=>'dd/MM/yyyy','message'=>'Ngày tháng không hợp lệ.'),
			array('email', 'email',
				'message'=>'Địa chỉ email không hợp lệ.'),
			array('email', 'checkAccountEmail'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, name, email, password, birthday, sex, avatar, cover, other, admin', 'safe', 'on'=>'search'),
			// verifyCode needs to be entered correctly
			//array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
			//array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
			//array('verifyCode', 'captcha', 'on'=>'capchatRequired'),
			array('verifyCode', 'captcha', 'allowEmpty' => !CCaptcha::checkRequirements(), 'on' => 'withCaptcha'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'comments' => array(self::HAS_MANY, 'Comment', 'user_id'),
			'friendships' => array(self::HAS_MANY, 'Friendship', 'friend_id'),
			'friendships1' => array(self::HAS_MANY, 'Friendship', 'user_id'),
			'listmusics' => array(self::HAS_MANY, 'Listmusic', 'user_id'),
			'messengers' => array(self::HAS_MANY, 'Messenger', 'friend_id'),
			'messengers1' => array(self::HAS_MANY, 'Messenger', 'user_id'),
			'musics' => array(self::HAS_MANY, 'Music', 'user_id'),
			'notifications' => array(self::HAS_MANY, 'Notification', 'user_id'),
			'tags' => array(self::HAS_MANY, 'Tag', 'user_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'name' => 'Họ và tên',
			'email' => 'Email',
			'password' => 'Mật khẩu',
			'birthday' => 'Ngày sinh',
			'sex' => 'Giới tính',
			'avatar' => 'Avatar',
			'cover' => 'Cover',
			'other' => 'Other',
			'admin' => 'Admin',
			'verifyCode'=>'Mã xác nhận',
			'lastlogin' => 'Đăng nhập cuối',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('email',$this->email,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('birthday',$this->birthday,true);
		$criteria->compare('sex',$this->sex);
		$criteria->compare('avatar',$this->avatar,true);
		$criteria->compare('cover',$this->cover,true);
		$criteria->compare('other',$this->other,true);
		$criteria->compare('admin',$this->admin);
		$criteria->compare('lastlogin',$this->lastlogin,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return User the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function add()
	{
		return $this->save(false);
	}

	public function addOtherInformation($text)
	{
		$ob = $this->findByPk($user_id);
		$ob->setAttribute('other',$text);
		$ob->save();
		return $ob->save();
	}

	public function view($user_id)
	{
		return $this->findByPk($user_id)->attributes;
	}

	public function remove($user_id)
	{
		return $this->deleteByPk($user_id);
	}

	public function edit()
	{
		$ob = $this->findByPk($user_id);
		$ob->attributes=$_POST['User'];
		return $ob->save();
	}

	public function searchByName($key)
	{
		$Criteria = new CDbCriteria();
		$Criteria->condition = "name like :key";
		$Criteria->params = array_merge($Criteria->params,array(":key"=>"%".$key."%"));
		$Criteria->order = '"name" ASC';
		$data = $this->findAll($Criteria);
		return $data;
	}

	public function checkAccountEmail($attribute,$params)
	{
		$user = @User::model()->find('LOWER(email)=?',array($this->email));
		if(isset($user))
		{
			$this->addError($attribute, 'Địa chỉ email này đã đăng ký');
		}
	}

	public function beforeSave()
	{
		//$date = '19/10/2013';
		$mysql_date = date('Y-m-d', strtotime(str_replace('/','-', $this->birthday)));
		$this->birthday = $mysql_date;
	    return true;
	}

	public function viewIdNameAvatar($user_id)
	{
		$user = $this->view($user_id);
		$return = array(
				'id'=>$user['id'],
				'name'=>$user['name'],
				'avatar'=>$user['avatar']
		);
		return $return;
	}

	public function changePassword($email,$password)
	{
		$user = @User::model()->find('LOWER(email)=?',array($email));
		if(isset($user))
		{
			$hash = CPasswordHelper::hashPassword($password);
			$user->setAttribute('password',$hash);
			return $user->save(false);
		}
		else
		{
			return false;
		}
	}
}
